package com.new2i.aop;
   
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.ModelAndView;

import com.new2i.model.DoctorEntity;
import com.new2i.util.Collection2JsonUtil;
import com.new2i.util.ConstantUtil.Platform;
import com.new2i.util.HttpSessionUtil;  

/**
 * Spring 方法拦截器
 *
 * @since 2014/11/08
 * @author 2i
 *
 */
public class MethodInterceptorImpl implements MethodInterceptor {

	private static Logger logger = Logger.getLogger(MethodInterceptorImpl.class);
	
	public Object invoke(MethodInvocation methodInvocation) throws Throwable {

		HttpServletResponse response = null;
		HttpServletRequest request = null; 
		
		logger.debug("当前方法:" + methodInvocation.getMethod().getName()); 
		Object[] arguments = methodInvocation.getArguments();
		for (int i = 0; i < arguments.length; i++) {
			if (arguments[i] instanceof HttpServletResponse) {
				response = (HttpServletResponse) arguments[i];
				response.setCharacterEncoding("UTF-8");
			}
			if (arguments[i] instanceof HttpServletRequest) {
				request = (HttpServletRequest) arguments[i];
			}
		}
   
		/**
		 * 登录拦截操作
		 */
		if (methodInvocation.getMethod().isAnnotationPresent(
				LoginInterceptor.class)) {
			logger.debug("这个方法需要拦截：" + methodInvocation.getMethod().getName());
			String sPlatId = request.getParameter("plat_id");  
			logger.debug("appplatform:" + sPlatId); 
			//拒绝未知平台访问
			int platId = sPlatId == null ? 0 : Integer.parseInt(sPlatId);   
			if(platId > Platform.Weixin.ordinal()) {
				String value = Collection2JsonUtil.byErrInfo(100, "拒绝未知平台访问");
				response.getWriter().write(value);
				return null;
			}  
			DoctorEntity doctor = HttpSessionUtil.getDoctorFromSession(request);
			if (doctor == null) {
				//若拦截的是页面,返回登录
				if(methodInvocation.getMethod().getName().contains("Page")) { 
					return new ModelAndView("/views/login.jsp");
				}else { 
					//若拦截的是接口, 返回未登录提示
					String value = Collection2JsonUtil.byErrInfo(101, "没有登录");
					response.getWriter().write(value); 
					return null;
				} 
			} else {
				for (int i = 0; i < arguments.length; i++) {
					if (arguments[i] instanceof DoctorEntity) {
						methodInvocation.getArguments()[i] = doctor;
					}
				}
			} 
		} 
		return methodInvocation.proceed();
	}
 
}
